package hot100;


/*
 * Author：江松
 * Date：2023/4/11 14:48
 *
 *
 路径总和3：无需从根节点到叶子节点的路径
 把每个点作为遍历起点，这样就能算出每条路径的和，然后比较




 */

public class Main437 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }



    int res=0;
    public void dfs(TreeNode root,long sum,int targetSum){
        if(root==null)return;
        sum+=root.val;
        if(sum==targetSum){
            res++;
        }
        dfs(root.left,sum,targetSum);
        dfs(root.right,sum,targetSum);
    }

    public int pathSum(TreeNode root, int targetSum) {
        if(root==null)return 0;
        dfs(root,0,targetSum);
        pathSum(root.left, targetSum);
        pathSum(root.right, targetSum);
        return res;
    }
}
